package com.soyea.controller;

import com.soyea.common.ApplicationContextHelper;
import com.soyea.common.JsonData;
import com.soyea.dao.SysAclMapper;
import com.soyea.dao.SysDeptMapper;
import com.soyea.dto.DeptLevelDTO;
import com.soyea.model.SysAcl;
import com.soyea.model.SysDept;
import com.soyea.param.TestVO;
import com.soyea.tree.BaseTreeObj;
import com.soyea.tree.TreeUtil;
import com.soyea.util.BeanValidator;
import com.soyea.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试Controller
 * Created by skh on 2018/1/3
 */
@Controller
@RequestMapping("/test")
@Slf4j
public class TestController {

	@Autowired
	private SysDeptMapper deptMapper;

	@RequestMapping("/hello.json")
	@ResponseBody
	public JsonData hello() {
		log.debug("debugMVC环境");
		return JsonData.success("hello permission");
	}

	@RequestMapping("/validate.json")
	@ResponseBody
	public JsonData validate(TestVO testVO) {
		log.debug("测试validate");
//		Map<String, String> errorMap = BeanValidator.validateObject(testVO);
//		if (MapUtils.isNotEmpty(errorMap)) {
//			for (Map.Entry<String, String> entry : errorMap.entrySet()) {
//				log.error("参数校验错误:{}->{}",entry.getKey(),entry.getValue());
//			}
//		}

		BeanValidator.check(testVO);
		return JsonData.success("test validate");
	}

	@RequestMapping("/jsonMapper.json")
	@ResponseBody
	public JsonData jsonMapper() {
		log.debug("测试jsonMapper");

		SysAclMapper sysAclMapper = ApplicationContextHelper.popBean(SysAclMapper.class);
		SysAcl sysAcl = sysAclMapper.selectByPrimaryKey(1);
		log.debug(JsonMapper.obj2String(sysAcl));

		return JsonData.success("hello jsonMapper");
	}


	@RequestMapping("/treeServiceTest.json")
	@ResponseBody
	public JsonData testTreeService() {
		List<SysDept> deptList = deptMapper.selectAllDept();

		List<BaseTreeObj> baseTreeGridList = new ArrayList<>();

		for (SysDept sysDept : deptList) {
			BaseTreeObj baseTreeObj = new BaseTreeObj();
			baseTreeObj.setId(sysDept.getId().toString());
			baseTreeObj.setParentId(sysDept.getParentId().toString());
			baseTreeObj.setName(sysDept.getName());
			baseTreeGridList.add(baseTreeObj);
		}

		List<BaseTreeObj> baseTreeObjs = TreeUtil.list2TreeConverter(baseTreeGridList, "0");
		return JsonData.success(baseTreeObjs);
	}

	@RequestMapping("/treeMybatis.json")
	@ResponseBody
	public JsonData testTreeMybaits() {

		List<DeptLevelDTO> deptLevelDTOList = deptMapper.queryDeptTreeList();

		return JsonData.success(deptLevelDTOList);
	}

	@RequestMapping("/treeChildMybatis.json")
	@ResponseBody
	public JsonData testChildMybaits(int id) {

		List<DeptLevelDTO> deptLevelDTOList = deptMapper.selectDeptChildrenById(id);

		return JsonData.success(deptLevelDTOList);
	}
}
